<template>
	<div class="netteach-standard">
		<!-- <div class="netteach-crumbs">
		    <router-link to="/netteach">网络教研</router-link>
		     <router-link to="/netteach/add">发起评课</router-link>
		    <span><i>></i>评课标准管理</span>
		</div> -->

		<div class="standard-content">
			<div class="standard-table">
				<h3>评估标准</h3>
				<template>
					<el-table :data="standardList" border style="width: 100%">
						<el-table-column
						prop="name"
						label="标准名称"
						width="180">
						</el-table-column>
						<el-table-column
						prop="user_name"
						label="撰写人"
						show-overflow-tooltip
						width="180">
						</el-table-column>

                        <!-- 单级 -->
						<el-table-column
						prop="subject_name"
						show-overflow-tooltip
                        v-if="!isMulti"
						label="适用">
						</el-table-column>
                        <!-- 多级 -->
						<el-table-column
						prop="classify_name"
						show-overflow-tooltip
                        v-else
						label="适用">
						</el-table-column>

						<el-table-column
						prop="use_count"
						show-overflow-tooltip
						label="使用次数">
						</el-table-column>
						<el-table-column
						prop="create_time"
						show-overflow-tooltip
						label="最近更新">
						</el-table-column>
						<el-table-column
						show-overflow-tooltip
						label="状态">
							 <template slot-scope="scope">
                            <!-- 多级 -->
							 	<span v-if="isMulti">{{scope.row.use_status == 1 ? '正在使用' : '未使用'}}</span>
                             <!-- 单级 -->
							 	<span v-else>{{scope.row.status == 1 ? '正在使用' : '未使用'}}</span>
							 </template>
						</el-table-column>
						<el-table-column
						      label="操作"
						      width="180">
						      <template slot-scope="scope">
						        <el-button type="text" size="small" @click="viewCriteriaShow(scope.row.id)">查看</el-button>
						        <router-link :to="{path: '/netteach/standard-edit', query: {id: scope.row.id}}">编辑</router-link>
						        <el-button type="text" size="danger" plain @click="removeDate(scope.row.id)">删除</el-button>
						      </template>
						</el-table-column>
					</el-table>
				</template>
				<el-pagination  v-if="totalSum > 10"
				    @size-change="sizeChange"
				    @current-change="currentChange"
				    :current-page="pageIndex"
				    :page-sizes="[100, 200, 300, 400]"
				    :page-size="pageSize"
				    layout="total, sizes, prev, pager, next, jumper"
				    :total="totalSum">
				</el-pagination>
			</div>

			<div class="standard-new">
				<h3>新增</h3>

				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="标准名称" prop="name">
						<el-input v-model.trim="ruleForm.name" placeholder="最多可以输入20个字符"></el-input>
					</el-form-item>

					<el-form-item label="标准总分" prop="score" class='standard-score'>
						<span>{{ruleForm.score}}  </span>分
					</el-form-item>

                    <!-- 单级 -->
                    <template v-if="!isMulti">
                        <el-form-item label="科目" prop="subject">
                            <el-select v-model="ruleForm.subject" placeholder="请选择科目">
                                <el-option
                                    v-for="item in subjectList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                    </el-option>
                                </el-select>
                        </el-form-item>
                    </template>
                    <!-- 多级 -->
                    <template v-else>
                        <el-form-item label="适用" prop="classify">
                            <el-select v-model="ruleForm.classify" placeholder="请选择分类">
                                <el-option
                                    v-for="item in classifyData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                            <el-button type="text" @click="classifyVisible=true">新建</el-button>
                        </el-form-item>
                    </template>

					<el-form-item label="标准总分" prop="" class="total-score" required>
							<el-tabs v-model="tabTempIndex" type="card" editable @edit="handleTabsEdit">
								<el-tab-pane
									v-for="(item, index) in subAlbumData"
									:label="item.title"
									:name="item.name"
									:key="index" >

									<div class="total-score-list">
										<ul>
											<li  v-for="(list,index2) in item.courseList">
												<div>
													<transition name="el-fade-in-linear">
														<el-form-item  :label="`评分标准`" label-width="100px"> 
															<el-input v-model.trim="list.name" placeholder="这是评分标准，20字符以内"  maxlength="20"></el-input>
														</el-form-item>
													</transition>
													<transition name="el-fade-in-linear" v-if="list.children.length === 0">
														<el-form-item  label="设置分数" label-width="80px"> 
															<el-input-number @change="changeTotal" v-model="list.score" controls-position="right" placeholder="设置分数" :min="0" :max="100"></el-input-number>
														</el-form-item>
													</transition>
												</div>

												<template  v-for="(node,index3) in list.children">
													<div>
														<transition name="el-fade-in-linear">
															<el-form-item  :label="`评分项${index3+1}`" label-width="100px"> 
																<el-input type="textarea" :rows="4" v-model.trim="node.content" placeholder="在此输入评分项内容，200字符以内"  maxlength="200"></el-input>
															</el-form-item>
														</transition>
														<transition name="el-fade-in-linear">
															<el-form-item  label="设置分数" label-width="80px"> 
																<el-input-number  @change="changeTotal" v-model="node.score" controls-position="right" placeholder="设置分数" :min="0" :max="100"></el-input-number>
															</el-form-item>
														</transition>
														<i class="el-icon-close" @click="closeCourseList(index, index2, index3)"></i>
													</div>
												</template>
												<div class="catalog-list-btn buttonCSS">
													<el-button type="primary" style="width:100px;" @click="newCourseList(index, index2)">添加子评分项</el-button>
												</div>
											</li>
										</ul>
									</div>
									
								</el-tab-pane>
							</el-tabs>
					</el-form-item>
	
					<el-form-item>
						<el-button type="primary" v-preventReClick='1000' @click="submitForm('ruleForm')">保存</el-button>
						<el-button type="primary" plain @click="resetForm('ruleForm')">取消</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>

        <el-dialog title="适用分类" class="classify-dialog" :visible.sync="classifyVisible" width="600px" :close-on-click-modal="false">
            <el-form :model="classifyForm" :rules="rules" ref="classifyForm" label-width="100px" class="classify-form">
                <el-form-item label="添加分类：" prop="newClassify">
                    <el-input v-model="classifyForm.newClassify" placeholder="自定义适用分类"></el-input>
                    <el-button type="primary" @click="addClassify('classifyForm')">添加</el-button>
                </el-form-item>
                <el-form-item label="管理分类：">
                    <template v-if="classifyData&&classifyData.length>0">
                        <el-tag  v-for="tag in classifyData" :key="tag.name" closable @close="delClassify(tag.id)">
                            {{tag.name}}
                        </el-tag>
                    </template>
                    <template v-else>
                        <span class="no-classify">暂无分类</span>
                    </template>
                </el-form-item>
            </el-form>
        </el-dialog>

		 <el-dialog
          title="查看评分标准"
          :visible.sync="viewCriteria"
          width="800px" :close-on-click-modal="false">
            <div class="substandard-title">
                <span>撰写人: {{viewCriteriaList.user_name}}</span>
                <span>分数: {{viewCriteriaList.total_score}}</span>
            </div>
            <template>
                <table class="standard-item">
                    <tr>
                        <th>评分标准</th>
                        <th>评分项</th>
                        <th>分数</th>
                    </tr>
                    <template v-for="(item, index) of viewCriteriaList.standard_item">
                        <template v-if="item.child.length === 0">
                            <tr>
                                <td>{{item.name}}</td>
                                <td>--</td>
                                <td>{{item.score}}</td>
                            </tr>
                        </template>
                        <template v-else>
                            <tr v-for="(child, index2) of item.child">
                                <td :rowspan="item.child.length" v-if="index2 === 0">{{item.name}}</td>
                                <td >{{child.name}}</td>
                                <td>{{child.score}}</td>
                            </tr>
                        </template>
                        
                    </template>
                </table>

            </template>
        </el-dialog>
	</div>
</template>

<script>
	
	export default {
		data(){
			return {
				standardList: [],
				page_page: 1,
				page_size: 10,
				total_sum: 0,
				ruleForm: {
					name: '',
					score: 0,
                    subject: '',
                    classify:'',
					arr: []
				},
				rules: {
					name: [
						{ required: true, message: '请输标准名称', trigger: 'blur' },
						{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
					],
					subject: [
						{ required: true, message: '请选择科目', trigger: 'change' }
                    ],
                    classify: [
						{ required: true, message: '请选择科目', trigger: 'change' }
                    ],
                    newClassify: [
						{ required: true, message: '请填写分类', trigger: 'blur' }
					],
				},
				subAlbumData: [
					{
						title:  '评分标准1',
						name: '1',
						courseList: [
							{	
								name: '',
								score: 0,
								children: []
							}
						]
					}
				],
				tabTempIndex: '1',
				viewCriteriaList: [],
				viewCriteria: false,
				pageIndex: 1,
				pageSize: 10,
				totalSum: 0,
                subjectList: [],
                // 多级：新建分类
                classifyVisible:false,
                classifyData: [],
                classifyForm:{
                    newClassify:"",
                },

				totalScore: 0,
				itemData: []
			}
		},
		watch: {
			'totalScore'(to, from){
				console.info(to)
			}
		},
		created(){
            this.getStandardList()
            if(this.isMulti){//多级
			    this.getClassifyData();
            }else{
			    this.getSubjectList();
            }
        },
        computed: {
            isMulti(){
                return this.$store.getters.isMulti;
            }  
        },
		methods: {
			changeTotal(){
				// console.log(this.subAlbumData);
				this.ruleForm.score = 0
				this.subAlbumData.forEach( (item)=>{
					item.courseList.forEach((item2)=>{
						this.ruleForm.score += parseInt(item2.score)
						item2.children.forEach((item3)=>{
							this.ruleForm.score += parseInt(item3.score)
						})
					})
				})


			},
			/*
				返回上一页
			*/
			goBack(){
				this.$router.back(-1)
			},
			/*
				计算评分标准总分 & 提取提交的健值
			*/
			totalStandards(){
				this.ruleForm.score = 0
				let arr = []
				for (let i = 0; i < this.subAlbumData.length; i++) {
					if (this.subAlbumData[i].courseList) {
						for (let j = 0; j < this.subAlbumData[i].courseList.length; j++) {

							if (this.subAlbumData[i].courseList[j].name === '' || this.subAlbumData[i].courseList[j].score === '') {
								this.$message.error(`标准总分的评分标准${i+1}--评分项${i+1} 或 分数不能为空`)
								
								return false
							}
							if (this.subAlbumData[i].courseList[j].children.length !== 0) {
								this.subAlbumData[i].courseList[j].score = 0
							}
							this.ruleForm.score += parseInt(this.subAlbumData[i].courseList[j].score);

							if (this.subAlbumData[i].courseList[j].children) {
								for (let k = 0; k < this.subAlbumData[i].courseList[j].children.length; k++) {

									if (this.subAlbumData[i].courseList[j].children[k].content === '' || this.subAlbumData[i].courseList[j].children[k].score === '') {
										this.$message.error(`标准总分的评分标准${i+1}--评分项${j+1} 或 分数不能为空`)
										return false
									}

									this.ruleForm.score += parseInt(this.subAlbumData[i].courseList[j].children[k].score)
								}
								
							}
							arr.push(this.subAlbumData[i].courseList[j])
						}
					}
						
				};
				this.ruleForm.arr = arr;
			},
			/*重新组建提交的数据方式*/
			setSubAlbumData(){
				
				for (let i = 0; i < this.subAlbumData.length; i++) {
					if (i === 0) {
						this.itemData.push({});
					}
					
					for (let j = 0; j < this.subAlbumData[i].courseList.length; j++) {

						this.itemData.push({
							name: this.subAlbumData[i].courseList[j].name,
							pid: 0,
							score: this.subAlbumData[i].courseList[j].score
						});
					}
				};

				for (let i = 0; i < this.subAlbumData.length; i++) {
					
					for (let j = 0; j < this.subAlbumData[i].courseList.length; j++) {

						if (this.subAlbumData[i].courseList[j].children.length !== 0) {
							for (let k = 0; k < this.subAlbumData[i].courseList[j].children.length; k++) {
								this.itemData.push({
									name: this.subAlbumData[i].courseList[j].children[k].content,
									pid: i+1,
									score: this.subAlbumData[i].courseList[j].children[k].score
								});
							}
						}
					}
				};
			},
			/*
				数据提交
			*/
			submitForm(formName) {

				this.$refs[formName].validate((valid) => {
					if (valid) {

						if (this.totalStandards() === false) return

						/*重新组建提交的数据方式*/
						this.setSubAlbumData()
						let success = (res=>{
							this.itemData = []
							this.$message.success(res.msg);
							this.getStandardList();
							this.ruleForm.name = '';
							this.ruleForm.score = 0;
							this.ruleForm.subject = '';
							this.tabTempIndex = '1'
							this.subAlbumData = [
								{
									title:  '评分标准1',
									name: '1',
									courseList: [
										{	
											name: '',
											score: 0,
											children: []
										}
									]
								}
							]

							this.$refs[formName].resetFields();
							
						});
						let fail = (res =>{
							this.$message.error(res.msg)
						})

                        let params = {
							id: this.$route.query.id,
							name: this.ruleForm.name,
							total_score: this.ruleForm.score,
							item_data: this.itemData,
							authority: 1,
							status: 1,
                            userid: this.$g.user_id,
                            subject_id:!this.isMulti?this.ruleForm.subject:null,//单级
                            classify_id:this.isMulti?this.ruleForm.classify:null,//多级
						};
						this.$ajax.post('api/network/eva_standard', params, {func:{success: success, fail: fail}})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			/*
				标准总分增删减
			*/
			handleTabsEdit(targetName, action) {
			
				if (action === 'add') {
					let newTabIndex = this.subAlbumData.length + 1;
			
					this.tabTempIndex = (newTabIndex).toString();
					
					this.subAlbumData.push({
						title:  `评分标准${newTabIndex}`,
						name: (newTabIndex).toString(),
						courseList: [
							{	
								name: '',
								score: 0,
								children: [
									// {
									// 	content: '',
									// 	score: ''
									// }
								]
								
							}
						]
					})
				}
			
				if (action === 'remove') {

					if (this.subAlbumData.length ===1) { 
						this.$message.error('评分标准不能为空');
						return 
					}
					var tabs = deep_clone( this.subAlbumData );
					var newtabs =  [];
					var continue_ornot = false;
					var ivn = 0;
					
					for (var i = 0; i <  tabs.length; i++) {

						if( parseInt(tabs[i].name) === parseInt(targetName)){
								
							continue_ornot = true;
							if( parseInt( this.tabTempIndex ) > 1 && i === parseInt( this.tabTempIndex ) ){

								this.tabTempIndex = (parseInt( this.tabTempIndex )).toString()
								// console.info(this.tabTempIndex ,1)
			
							}else if( parseInt( this.tabTempIndex ) > i ){
								this.tabTempIndex = (parseInt( this.tabTempIndex) -1).toString()
									// console.info(this.tabTempIndex ,2)
							}
							continue;
						}else{
							ivn = ivn+1;
							if( continue_ornot ){
								tabs[i].title = `评分标准${ivn}`;
								tabs[i].name = (ivn).toString();
							}
							newtabs.push( tabs[i] );
						}
					}
				
					this.subAlbumData = deep_clone( newtabs );
				}
			},
			newCourseList(index, index2){

				this.subAlbumData[index].courseList[index2].children.push({
					content: '',
					score: ''
				})

				if (this.subAlbumData[index].courseList[index2].children.length !== 0 ) {
					this.subAlbumData[index].courseList[index2].score = 0
				}
			},
			/*
				
			 */
			closeCourseList(index, index2, index3){
				this.subAlbumData[index].courseList[index2].children.splice(index3, 1)
				this.subAlbumData[index].courseList[index2].children.content = ''
				this.subAlbumData[index].courseList[index2].children.score = 0
			},
			/*
				查看评分标准
			 */
			substandardSee(){
				this.substandard = true	
			},

			/*
				请求评分标准列表
			*/
			getStandardList(){
				let success = (res=>{
					this.standardList = res.data.data;
					this.pageIndex = parseInt(res.data.page_index);
					this.totalSum = parseInt(res.data.data_sum)
				});

				this.$ajax({
					url: 'api/network/eva_standard',
					method: 'get',
					params: {
						page_index: this.pageIndex,
						page_size: this.pageSize,
						status: 1,
                        user_id: this.user_id,
                        // classify_id:this.isMulti?this.ruleForm.classify:null,
					},
					func: {success: success}
				})
			},
			sizeChange(val) {
				this.pageSize = val;
				this.getStandardList()
			},
			currentChange(val) {
				this.pageIndex = val;
				this.getStandardList()
			},
			/*
					是否删除该评估标准
			 */
			removeDate(id){
				this.$confirm('是否删除该记录?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'confirm-them',
				}).then(() => {
					let success = (res=>{
                        this.$message.success('删除成功');
						this.getStandardList()
					});

					this.$ajax({
						url: 'api/network/eva_standard',
						method: 'delete',
						params: {id: id},
						func: {success: success}
					})
				
				}).catch(() => {});
			},
			/*
				查看对应ID的评估标准内容
			*/
			viewCriteriaShow(id){

			    this.viewCriteria = true;

			    let success = (res =>{
			        this.viewCriteriaList = res.data
			    });

			    this.$ajax({
			        url: 'api/network/standard_detail',
			        method: 'get',
			        params: {id: id},
			        func: {success: success}
			    })
			},
			/*
			    请求科目
			*/
			getSubjectList(){
			    let success = (res=>{
			        this.subjectList = res.data;
			        // this.subjectList.unshift({'id': 0, 'name': '所以科目'})
			    });

			    this.$ajax({
			        url: 'api/cate/subject',
			        method: 'get',
			        params: {},
			        func: {success: success}
			    })
            },
            /*
			    多级：获取分类
			*/
			getClassifyData(){
			    let success = (res=>{
			        this.classifyData = res.data;
			    });

			    this.$ajax({
			        url: 'api/network/eva_standard_classify',
			        method: 'get',
			        params: {},
			        func: {success: success}
			    })
            },
            /*
			    多级：新增分类
			*/
            addClassify(formName){
                if(this.classifyForm.newClassify.trim()===''){
                    this.$message.warning("分类内容不能为空格");
                    return;
                }   
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                            let success = (res=>{
                                this.$message.success(res.msg);
                                this.getClassifyData();
                                this.classifyForm.newClassify = "";
                            });		

                            let fail = (res=>{
                                this.classifyForm.newClassify = "";
                                this.$message.error(res.msg);
                            });
                            let params = {name:this.classifyForm.newClassify};
                            this.$ajax.post('api/network/eva_standard_classify', params, {func:{success: success, fail: fail}})
                    }
                })

            },
            /*
			    多级：删除分类
			*/
            delClassify(id){
                let success = (res=>{
                    this.$message.success(res.msg);
                    this.getClassifyData();
                });		

                let fail = (res=>{
                    this.$message.error(res.msg);
                });
                this.$ajax({
                    url: 'api/network/eva_standard_classify',
                    method: 'delete',
                    params: {classify_id: id},
                    func: {success: success, fail: fail}
                })

            }
		}


	}
</script>
<style lang="scss">
    .classify-dialog{

        .el-input{
            width: 300px;
            margin-right: 30px;
        }

        .el-tag{
            margin: 2px;
        }
    }
</style>